<template>
  <div>
    <a-card>
      <a-tabs v-model:active-key="activeKey" @change="onChangeTab">
        <a-tab-pane :key="0" tab="门诊" />
        <a-tab-pane :key="1" tab="住院" />
        <a-tab-pane :key="2" tab="体检" />
      </a-tabs>
      <div class="flex flex-col h-full">
        <SearchContainer @reset="() => formRef.resetFields()" @search="getData">
          <a-form ref="formRef" class="form-style-flex" :model="formState">
            <a-form-item name="pyjm">
              <a-input v-model:value="formState.pyjm" class="w-80" :placeholder="activeKey === 1 ? '姓名/助记码/手机号/床位号' : '姓名/助记码/手机号'" />
            </a-form-item>
            <a-form-item name="stdate" label="检验日期" class="mx-3 w-80">
              <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-form-item name="categroyCode" label="检验大类" class="w-80">
              <a-select v-model:value="formState.categroyCode" placeholder="请选择" class="w-40">
                <a-select-option v-for="item in categoryList" :key="item" :value="item.categroyCode">{{ item.categroyName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </SearchContainer>
        <a-card class="mt-2 flex-1">
          <div class="absolute top-[-9999px] hidden">
            <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
            <PrintView id="printMe" :print-data="printData" />
          </div>
          <BaseTable fill :loading="loading" :column-code="columnCode" :data-source="tableData" :scroll="{ x: 2100 }" :pagination="pagination" bordered>
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'shzt'">
                <a-tag v-if="record.auditName" color="green">已审核</a-tag>
                <a-tag v-else color="red">未审核</a-tag>
              </template>
              <template v-if="column.dataIndex === 'status'">
                <a-tag v-if="record.status === '0'" color="blue">未审核</a-tag>
                <a-tag v-if="record.status === '1'" color="green">已审核</a-tag>
                <a-tag v-if="record.status === '2'" color="red">已审核</a-tag>
              </template>
              <template v-if="column.dataIndex === 'recordCode'">
                <PopoverTable :config="detailConfig" :params="{ brId: record.brId, lsh: record.lsh, xb: record.brXb }" :width="1000">
                  <template #bodyCell="{ column: popColumn, record: popRecord }">
                    <template v-if="popColumn.dataIndex === 'lastResult'">
                      <div class="flex">
                        <div class="mr-5">{{ popRecord.lastResult }}</div>
                        <div class="tip absolute right-4 text-2xl top-2 z-10">
                          <div v-if="popRecord.tips === '1'" class="text-green-500">↓</div>
                          <div v-if="popRecord.tips === '2'" class="text-red-500">↑</div>
                        </div>
                      </div>
                    </template>
                  </template>
                  {{ record.recordCode }}
                </PopoverTable>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" size="small" @click="onPrint(record, '1')">预览</a-button>
                <a-button type="link" size="small" @click="onPrint(record, '2')">打印</a-button>
                <a-button type="link" size="small" @click="onExport(record)">导出</a-button>
              </template>
            </template>
          </BaseTable>
        </a-card>
      </div>
    </a-card>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { chunk } from 'lodash-es'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'
import { post, http } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import PrintView from './PrintView.vue'

const categoryList = ref([])
const printData = ref({})
const printMe = ref()
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const formRef = ref(null)
const activeKey = ref(0)
const columnCode = ref('000185')
const detailConfig = ref({
  url: '/lis/LisRecord/getLisItemRecordList',
  columnCode: '000186',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      NO: index + 1
    }))
  }
})

const { loading, pagination, getData, tableData } = useTable({
  url: '/lis/LisApply/getLisReportList',
  formatParams: () => {
    return {
      applyPath: activeKey.value,
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1],
      pyjm: formState.value?.pyjm,
      categroyCode: formState.value?.categroyCode,
      wardName: formState.value?.wardName,
      lastBedCode: formState.value?.lastBedCode
    }
  }
})

const getCategoryList = async () => {
  const { code, data, msg } = await post('/lis/InstrumentType/getLisCategroyList', { pageNum: 1, pageSize: 999 })
  if (code !== 0) return message.error(msg)
  categoryList.value = data
  // formState.value.categoryCode = data[0]?.categoryCode
}

const onPrint = async (row, dylx) => {
  const { code, msg, data } = await post('/lis/lisPrint/printLisRecord', { lsh: row.lsh, barCode: row.barCode, dylx })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    const dataJson = JSON.parse(data)
    const chunkList = chunk(dataJson.printData.lisRecordItemList, 28)
    for (let i = 0; i < chunkList.length; i++) {
      printData.value = {
        ...dataJson,
        printData: {
          ...dataJson.printData,
          lisRecordItemList: chunkList[i]
        }
      }
      await new Promise((resolve) => setTimeout(resolve, 1000))
      setPrintSize('A5', 'landscape')
      printMe.value.$el.click()
      await new Promise((resolve) => setTimeout(resolve, 2000))
    }
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
const onChangeTab = (e) => {
  if (e === 0) {
    columnCode.value = '000185'
  } else if (e === 1) {
    columnCode.value = '000492'
  }
  getData()
}
// 导出
const onExport = (row) => {
  http
    .post(
      '/lis/LisRecord/exportLisReportDetails',
      {
        parameters: {
          brId: row.brId,
          lsh: row.lsh,
          xb: row.brXb
        },
        tblcode: '000186'
      },
      { responseType: 'blob' }
    )
    .then((res) => {
      const href = URL.createObjectURL(res.data)
      const element = document.createElement('a')
      element.download = '检验报告明细' + '.xlsx'
      element.href = href
      element.click()
    })
    .catch(() => {
      message.error('导出失败，请稍后重试！')
    })
}

onMounted(() => {
  getCategoryList()
  getData()
})
</script>
